import * as React from 'react';
import { RouteProps } from 'react-router';
import { Route, Redirect } from 'react-router-dom';
import Authorized from './Authorized';

type authorityFN = (currentAuthority?: string) => boolean;
type authority = string | Array<string> | authorityFN | Promise<any>;

export interface AuthorizedRouteProps extends RouteProps {
  authority: authority;
  redirectPath: any;
}

class AuthorizedRoute extends React.Component<AuthorizedRouteProps> {
  render() {
    const { component: Component, render, authority, redirectPath, ...rest } = this.props;
    return (
      <Authorized
        authority={authority}
        noMatch={<Route {...rest} render={() => <Redirect to={{ pathname: redirectPath }} />} />}>
        <Route
          {...rest}
          render={props => (Component ? <Component {...props} /> : (render as any)(props))}
        />
      </Authorized>
    );
  }
}

export default AuthorizedRoute;
